//
//  3DZUSAN.m
//  EasyToo
//
//  Created by linshengqin on 13-6-24.
//
//

#import "3DZUSAN.h"
#import <AudioToolbox/AudioToolbox.h>
#import "DeviceUtil.h"
#import "LotteryCount.h"
#import <QuartzCore/QuartzCore.h>
#import "CaiPiaoConfirmViewController.h"
#import "CaiPiaoLogic.h"
@implementation _DZUSAN
{
    int randArray[10];
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self setBackgroundColor:BackgroundColor];
    }
    return self;
}

/*
 - (void)viewDidLoad
 {
 [super viewDidLoad];
 [self initLable];
 [self initButton];
 // Do any additional setup after loading the view.
 [self becomeFirstResponder]; // for shaking
 }
 */
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    [self initView];
}


-(void) initView
{
    [self initData];
    [self initMainView];
    [self initButton];
//    [self initToolBar];
    [self initLable];
}

-(void)initData
{
    caipiao_model = [CaiPiaoModel sharedata];
    [caipiao_model resetPara];
}

-(void)initMainView
{
    _bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [DeviceUtil getScreenWidth], [DeviceUtil getScreenHeight])];
    [self addSubview:_bgScrollView];
    _bgScrollView.contentSize = CGSizeMake(320, 700);
    _bgScrollView.showsVerticalScrollIndicator = YES;
    
    _viewBall = [[UIView alloc]initWithFrame:CGRectMake(20, 50, _bgScrollView.frame.size.width-40, 80)];
    _viewBall.layer.borderColor = [UIColor grayColor].CGColor;
    _viewBall.layer.borderWidth = 1 ;
    _viewBall.layer.cornerRadius = 10 ;
    [_bgScrollView addSubview:_viewBall];
    
}
#define MAX_NUM 10
-(void) initButton
{
    
    /*红球*/
    int tag = 0;
    int num = 0;
    _btnArray = [[NSMutableArray alloc]init];
    while (num<MAX_NUM)
    {
        m_button = [UIButton buttonWithType:UIButtonTypeCustom];
        m_button.frame = CGRectMake(30+(tag%5)*40, (tag/5)*40, 40, 40);
        m_button.tag=tag;
        // Set the font and color
        [m_button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [m_button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        
        m_button.titleLabel.font = [UIFont boldSystemFontOfSize:10.0f];
        
        [m_button setTitle:[NSString stringWithFormat:@"%d",num] forState:UIControlStateNormal];
        
        [m_button setBackgroundColor:[UIColor clearColor]];
        [m_button setBackgroundImage:[UIImage imageNamed:@"cp_ssqiu_bg"] forState:UIControlStateNormal ];
        [m_button setBackgroundImage:[UIImage imageNamed:@"cp_ssqiured_bg"]forState:UIControlStateSelected];
        
        [m_button addTarget:self action:@selector(touristEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_btnArray addObject:m_button];
        [_viewBall addSubview:m_button];
        num++;
        tag++;
    }
    UIButton* m_cleanall = [UIButton buttonWithType:UIButtonTypeCustom];
    m_cleanall.frame = CGRectMake(40,_viewBall.frame.origin.y+_viewBall.frame.size.height+20, 100, 40);
    [m_cleanall setTitle:[NSString stringWithFormat:@"%@",@"清空全部"] forState:UIControlStateNormal];
    [m_cleanall setBackgroundColor:[UIColor clearColor]];
    [m_cleanall setBackgroundImage:[UIImage imageNamed:@"clear_all"] forState:UIControlStateNormal ];
    [m_cleanall addTarget:self action:@selector(onClickCancle:) forControlEvents:UIControlEventTouchUpInside];
    [_bgScrollView addSubview:m_cleanall];
    
    UIButton* m_confirm = [UIButton buttonWithType:UIButtonTypeCustom];
    m_confirm.frame = CGRectMake([DeviceUtil getScreenWidth]/2+20, _viewBall.frame.origin.y+_viewBall.frame.size.height+20, 100, 40);
    [m_confirm setTitle:[NSString stringWithFormat:@"%@",@"下一步"] forState:UIControlStateNormal];
    [m_confirm setBackgroundColor:[UIColor clearColor]];
    [m_confirm setBackgroundImage:[UIImage imageNamed:@"xyb"] forState:UIControlStateNormal ];
    [m_confirm addTarget:self action:@selector(onClickConfirm:) forControlEvents:UIControlEventTouchUpInside];
    [_bgScrollView addSubview:m_confirm];
}
-(void) initToolBar
{
    _myToolbar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, [DeviceUtil getScreenHeight]-135/*375*/, [DeviceUtil getScreenWidth]-30, 44)]autorelease];
	_myToolbar.barStyle = UIBarStyleBlackOpaque;
    _toolbarArray = [[NSMutableArray alloc] init];
    [_toolbarArray addObject:[[UIBarButtonItem alloc] initWithTitle:@"清空" style:UIBarButtonItemStyleDone target:self action:@selector(onClickCancle:)]];
    
    
    _toolbarLabel = [[[UILabel alloc] initWithFrame:CGRectMake(100.0f, 100.0f, 200.0f, 30.0f)]autorelease];
    _toolbarLabel.font=[UIFont systemFontOfSize:16];
    _toolbarLabel.backgroundColor = [UIColor clearColor];
    _toolbarLabel.textAlignment=NSTextAlignmentCenter;
    _toolbarLabel.text  = @"共0注 0元";
    _toolbarLabel.textColor = [UIColor whiteColor];
    UIBarButtonItem *myButtonItem = [[[UIBarButtonItem alloc]initWithCustomView:_toolbarLabel]autorelease];
    
    [_toolbarArray addObject: myButtonItem]; //添加文本
    // flex item used to separate the left groups items and right grouped items
	UIBarButtonItem *flexItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                              target:nil
                                                                              action:nil]autorelease];
    [_toolbarArray addObject:flexItem];
    [_toolbarArray addObject:[[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(onClickConfirm:)]];
    
    
    
    [_myToolbar setItems:_toolbarArray];
    
    [self addSubview:_myToolbar];
    
}

-(void) initLable
{
    tips = [[[UILabel alloc] initWithFrame:CGRectMake(30, 10, 170, 30)]autorelease];
    tips.text =  @"至少选择两个号码";
    tips.font = [UIFont boldSystemFontOfSize:14.0f];  //UILabel的字体大小
    tips.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
    [tips setBackgroundColor:[UIColor clearColor]];
    [_bgScrollView addSubview:tips];
    
    UIButton* tips_button = [UIButton buttonWithType:UIButtonTypeCustom];
    tips_button.frame = CGRectMake( 220, 10,70, 30);
    tips_button.titleLabel.font = [UIFont boldSystemFontOfSize:12.0f];
    
    [tips_button setTitle:[NSString stringWithFormat:@"%@",@"机选"] forState:UIControlStateNormal];
    [tips_button setBackgroundColor:[UIColor clearColor]];
    [tips_button setBackgroundImage:[UIImage imageNamed:@"cp_sshongq_bg"] forState:UIControlStateNormal ];
    [tips_button addTarget:self action:@selector(randBall:) forControlEvents:UIControlEventTouchUpInside];
    [_bgScrollView addSubview:tips_button];
}

-(void)randBall:(id)sender
{
    for (UIButton *button in _btnArray) {
        button.selected = NO;
    }
    for( int i=0;i<10;i++)
    {
        randArray[i]=i;
    }
    int x = arc4random() % 10;
    UIButton* btn = [_btnArray objectAtIndex:x];
    btn.selected = YES;
    
    int y = arc4random() % 10;
    while( x == y )
    {
        y = arc4random() % 10;
    }
    btn = [_btnArray objectAtIndex:y];
    btn.selected = YES;
    [self touristEvent:nil];
}
-(void)touristEvent:(id)sender
{
    UIButton *button = (UIButton *)sender;
    button.selected = !button.selected;
    
    
    int count = 0;
    for (UIButton *button in _btnArray) {
        if( button.selected == YES )
            count++;
    }
    long m_totalCount = getLotteryCount(count,2)*2;
    long m_totalPrice = m_totalCount*2;
//    self.fatherView.navigationItem.title = [NSString stringWithFormat:@"共%ld注 %ld元",totalCount,totalPrice];
    if(totalPrice > 20000)
    {
        printf("不能超过20000元\n");
        UIAlertView* baseAlert = [[[UIAlertView alloc] initWithTitle:@"不能超过20000元" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil] autorelease];
        [baseAlert show];
        button.selected = !button.selected;
    }
    else
    {
        totalCount = m_totalCount;
        totalPrice = m_totalPrice;
        self.fatherView.navigationItem.title = [NSString stringWithFormat:@"共%ld注 %ld元",totalCount,totalPrice];
    }
}


-(void)onClickCancle:(id)sender
{
    printf("cancle\n");
    for (UIButton *button in _btnArray) {
        button.selected = NO;
    }
    
    _toolbarLabel.text = [NSString stringWithFormat:@"共0注 0元"];
}

-(void)onClickConfirm:(id)sender
{
    printf("zusan confirm\n");
    int count = 0;
    for (UIButton *button in _btnArray) {
        if( button.selected == YES )
            count++;
    }
    if( count < 2)
    {
        UIAlertView* baseAlert = [[[UIAlertView alloc] initWithTitle:@"至少选择2个球" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil] autorelease];
        [baseAlert show];
        return;
    }
    totalCount = getLotteryCount(count,2)*2;
    totalPrice = totalCount*2;
    
    if( [[CaiPiaoLogic shareInstance] cmpTime] != NSOrderedAscending )
     {
         UIAlertView* baseAlert = [[[UIAlertView alloc] initWithTitle:@"投注时间已过" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil] autorelease];
         [baseAlert show];
         return;
     }
    NSMutableString* result = [[[NSMutableString alloc]init]autorelease];
    int flag = 1;
    for (UIButton *button in _btnArray) {
        if(button.selected)
        {
            if( flag )
            {
                [result appendString:button.titleLabel.text];
                flag = 0;
            }
            else
            {
                [result appendFormat:@",%@",button.titleLabel.text];
            }
            button.selected = NO;
        }
    }
    [caipiao_model.stakeList addObject:result];
    [caipiao_model.listNum addObject:[NSNumber numberWithLong:totalCount]];
    [caipiao_model.listPrice addObject:[NSNumber numberWithLong:totalPrice]];
    caipiao_model.lType = 2;

    CaiPiaoConfirmViewController  *confirm = [[[CaiPiaoConfirmViewController alloc]init]autorelease];
    [self.fatherView.navigationController pushViewController:confirm animated:YES];
}



#pragma mark shark delegate

- (BOOL) canBecomeFirstResponder
{
    return YES;
}

- (void) motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event

{
    
    //检测到摇动
    printf("shaking begin!\n");
    
    
}



- (void) motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event

{
    
    //摇动取消
    
}



- (void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event

{
    
    //摇动结束
    
    if (event.subtype == UIEventSubtypeMotionShake) {
        
        //something happens
        printf("shaking end!\n");
        for (UIButton *button in _btnArray) {
            button.selected = NO;
        }
        
        _toolbarLabel.text = [NSString stringWithFormat:@"共%d注 %d元",0,0];
        for( int i=0;i<10;i++)
        {
            randArray[i]=i;
        }
        
        int x = arc4random() % 10;
        UIButton* btn = [_btnArray objectAtIndex:x];
        btn.selected = YES;
        
        int y = arc4random() % 10;
        while( x == y )
        {
            y = arc4random() % 10;
        }
        btn = [_btnArray objectAtIndex:y];
        btn.selected = YES;
        [self randBall:nil];
        [self touristEvent:nil];
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
    
}

-(void)onTabSelected:(id)sender
{
    //    UISegmentedControl *control = (UISegmentedControl *)sender;
}
@end
